﻿// 修复后的 HighPerformanceDataAdapter.cs - 清理所有编译错误

using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.Util;
using MultiDAQ_Analysis.View;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using static UltraHighPerformanceChannelParser;

/// <summary>
/// 高性能数据适配器 - 清理版，单一内存统计系统 + 视图映射
/// </summary>
public class HighPerformanceDataAdapter : IDisposable
{
    #region 配置常量
    private const int UPDATE_INTERVAL_MS = 1000;
    private const int BATCH_SIZE = 10000;
    #endregion

    #region 字段
    private readonly PlotViewPanel _plotPanel;
    private readonly UltraHighPerformanceChannelParser _parser;
    private readonly Thread _adapterThread;
    private readonly ConcurrentDictionary<int, ConcurrentQueue<double>> _channelDataQueues;
    private readonly Timer _updateTimer;
    private volatile bool _isRunning;

    // 统计相关字段
    private readonly UcCenterView _centerView;
    private volatile bool _statisticsEnabled = true;
    private volatile bool _enableDebugOutput = false;

    // 添加统计字段
    private readonly AdapterStatistics _adapterStatistics;

    // 阈值配置
    private readonly Dictionary<int, ThresholdData> _channelThresholds;
    private readonly Timer _thresholdRefreshTimer;
    private DateTime _lastThresholdLoadTime;

    // 新增视图映射字段
    private readonly Timer _statisticsUpdateTimer;

    // 性能统计
    private long _totalPointsProcessed;
    private long _totalPointsMapped;
    private long _totalUpdates;
    private DateTime _startTime;

    // 动态线程管理
    private readonly int _minThreads = 1;
    private readonly int _maxThreads = Environment.ProcessorCount * 2;
    private volatile int _currentThreadCount = 1;
    private Thread[] _processingThreads;
    private volatile bool _processingActive = false;
    private readonly object _threadAdjustLock = new object();
    private Timer _threadAdjustTimer;
    private volatile int _totalQueueSize = 0;
    private readonly int[] _queueSizeHistory = new int[10];
    private int _historyIndex = 0;

    // 性能监控相关
    private readonly Stopwatch _performanceStopwatch = new Stopwatch();
    private long _lastPerformanceCheck;
    #endregion

    #region 构造函数
    public HighPerformanceDataAdapter(PlotViewPanel plotPanel, UltraHighPerformanceChannelParser parser)
        : this(plotPanel, parser, null)
    {
    }

    public HighPerformanceDataAdapter(PlotViewPanel plotPanel, UltraHighPerformanceChannelParser parser, UcCenterView centerView)
    {
        _plotPanel = plotPanel ?? throw new ArgumentNullException(nameof(plotPanel));
        _parser = parser ?? throw new ArgumentNullException(nameof(parser));
        _centerView = centerView;

        _channelDataQueues = new ConcurrentDictionary<int, ConcurrentQueue<double>>();
        _channelThresholds = new Dictionary<int, ThresholdData>();

        // 初始化数据结构
        for (int i = 1; i <= 8; i++)
        {
            _channelDataQueues[i] = new ConcurrentQueue<double>();
        }

        if (AppConfig.LogPrint == 1)
        {
            Console.WriteLine($"[适配器初始化] 初始化完成，统计通道1-8");
        }

        LoadChannelThresholds();

        _adapterThread = new Thread(DataProcessingLoop)
        {
            IsBackground = true,
            Name = "CleanDataAdapter",
            Priority = ThreadPriority.Normal
        };

        _updateTimer = new Timer(UpdateDisplayCallback, null, Timeout.Infinite, Timeout.Infinite);

        if (_centerView != null)
        {
            _thresholdRefreshTimer = new Timer(RefreshThresholdsCallback, null, Timeout.Infinite, Timeout.Infinite);
            _statisticsUpdateTimer = new Timer(MapStatisticsToViewCallback, null, Timeout.Infinite, Timeout.Infinite);
        }

        _startTime = DateTime.Now;
        _adapterStatistics = new AdapterStatistics();
        _performanceStopwatch = new Stopwatch();

        if (AppConfig.LogPrint == 1)
        {
            Console.WriteLine($"[清理版适配器] 初始化完成，统计功能: {(_centerView != null ? "启用" : "禁用")}");
        }
    }
    #endregion

    #region 阈值配置管理
    private void LoadChannelThresholds()
    {
        try
        {
            var channelDataList = ChannelDataManager.LoadAllChannelData();

            lock (_channelThresholds)
            {
                _channelThresholds.Clear();

                for (int i = 0; i < channelDataList.Count && i < 8; i++)
                {
                    _channelThresholds[i] = channelDataList[i].Thresholds;
                }
            }

            _lastThresholdLoadTime = DateTime.Now;
            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"[清理版适配器] 已加载 {_channelThresholds.Count} 个通道的阈值配置");
            }
        }
        catch (Exception ex)
        {
            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"[清理版适配器] 加载阈值配置失败: {ex.Message}");
            }
        }
    }

    private void RefreshThresholdsCallback(object state)
    {
        if (_statisticsEnabled && AppConfig.LogPrint == 1)
        {
            LoadChannelThresholds();
        }
    }

    private ThresholdData GetChannelThresholdsSafe(int channelIndex)
    {
        if (channelIndex < 0 || channelIndex >= 8)
        {
            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"[阈值获取] 无效通道索引: {channelIndex}");
            }
            return new ThresholdData();
        }

        lock (_channelThresholds)
        {
            if (_channelThresholds.ContainsKey(channelIndex))
            {
                var threshold = _channelThresholds[channelIndex];
                return threshold;
            }
        }

        if (AppConfig.LogPrint == 1)
        {
            Console.WriteLine($"[阈值获取] 通道{channelIndex}未配置阈值，使用默认值");
        }
        return new ThresholdData();
    }

    #endregion

    #region 启动和停止
    public void Start()
    {
        if (_isRunning) return;

        _isRunning = true;
        _processingActive = true;
        _startTime = DateTime.Now;
        _performanceStopwatch.Start();

        _plotPanel.StopSimulation();
        _plotPanel.ClearAllData();
        _plotPanel.UpdateHistogram();

        _adapterThread.Start();

        _currentThreadCount = _minThreads;
        StartProcessingThreads(_currentThreadCount);

        if (AppConfig.LogPrint == 1)
        {
            _threadAdjustTimer = new Timer(AdjustThreadCount, null, 500, 500);
        }

        if (_centerView != null && _statisticsEnabled)
        {
            _thresholdRefreshTimer?.Change(30000, 30000);
            _statisticsUpdateTimer?.Change(2000, 2000); // 每2秒映射统计数据到视图
        }

        if (AppConfig.LogPrint == 1)
        {
            Console.WriteLine($"[清理版适配器] 已启动，初始线程数: {_currentThreadCount}");
        }
    }

    public void Stop()
    {
        if (!_isRunning) return;

        _isRunning = false;
        _processingActive = false;

        _threadAdjustTimer?.Change(Timeout.Infinite, Timeout.Infinite);
        _updateTimer?.Change(Timeout.Infinite, Timeout.Infinite);
        _thresholdRefreshTimer?.Change(Timeout.Infinite, Timeout.Infinite);
        _statisticsUpdateTimer?.Change(Timeout.Infinite, Timeout.Infinite);
        _performanceStopwatch.Stop();

        StopAllProcessingThreads();

        if (_adapterThread.IsAlive)
        {
            _adapterThread.Join(3000);
        }

        // 停止前最后一次映射统计数据
        if (AppConfig.LogPrint == 1)
        {
            MapCurrentStatisticsToView();
        }

        DrainAllQueuesParallel();

        // 打印最终统计报告
        if (AppConfig.LogPrint == 1)
        {
            _adapterStatistics.PrintFinalStatistics();
            Console.WriteLine($"[清理版适配器] 已停止");
        }
    }
    #endregion

    #region 动态线程管理
    private void AdjustThreadCount(object state)
    {
        if (!_processingActive) return;

        lock (_threadAdjustLock)
        {
            try
            {
                int currentQueueSize = CalculateTotalQueueSize();
                _totalQueueSize = currentQueueSize;

                _queueSizeHistory[_historyIndex] = currentQueueSize;
                _historyIndex = (_historyIndex + 1) % _queueSizeHistory.Length;

                int avgQueueSize = _queueSizeHistory.Sum() / _queueSizeHistory.Length;
                int idealThreadCount = CalculateIdealThreadCount(avgQueueSize);

                if (idealThreadCount != _currentThreadCount)
                {
                    AdjustThreadsTo(idealThreadCount);
                }
            }
            catch (Exception ex)
            {
                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[线程调整错误] {ex.Message}");
                }
            }
        }
    }

    private int CalculateTotalQueueSize()
    {
        int total = 0;
        for (int channel = 1; channel <= 8; channel++)
        {
            if (_channelDataQueues.ContainsKey(channel))
            {
                total += _channelDataQueues[channel].Count;
            }
        }
        return total;
    }

    private int CalculateIdealThreadCount(int avgQueueSize)
    {
        int idealCount;

        if (avgQueueSize == 0)
        {
            idealCount = _minThreads;
        }
        else if (avgQueueSize < 1000)
        {
            idealCount = Math.Max(_minThreads, avgQueueSize / 500 + 1);
        }
        else if (avgQueueSize < 5000)
        {
            idealCount = Math.Min(_maxThreads, avgQueueSize / 1000 + 2);
        }
        else
        {
            idealCount = _maxThreads;
        }

        return Math.Max(_minThreads, Math.Min(_maxThreads, idealCount));
    }

    private void AdjustThreadsTo(int targetCount)
    {
        if (targetCount == _currentThreadCount) return;

        try
        {
            if (targetCount > _currentThreadCount)
            {
                AddThreads(targetCount - _currentThreadCount);
            }
            else
            {
                RemoveThreads(_currentThreadCount - targetCount);
            }

            _currentThreadCount = targetCount;
        }
        catch (Exception ex)
        {
            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"[线程调整失败] {ex.Message}");
            }
        }
    }

    private void StartProcessingThreads(int threadCount)
    {
        _processingThreads = new Thread[_maxThreads];

        for (int i = 0; i < threadCount; i++)
        {
            CreateAndStartThread(i);
        }
    }

    private void CreateAndStartThread(int threadId)
    {
        _processingThreads[threadId] = new Thread(() => QueueProcessingLoop(threadId))
        {
            IsBackground = true,
            Name = $"DynamicProcessor-{threadId}",
            Priority = ThreadPriority.AboveNormal
        };
        _processingThreads[threadId].Start();
    }

    private void AddThreads(int count)
    {
        for (int i = 0; i < count; i++)
        {
            int newThreadId = _currentThreadCount + i;
            if (newThreadId < _maxThreads)
            {
                CreateAndStartThread(newThreadId);
            }
        }
    }

    private void RemoveThreads(int count)
    {
        for (int i = _currentThreadCount - 1; i >= _currentThreadCount - count && i >= _minThreads; i--)
        {
            if (_processingThreads[i] != null && _processingThreads[i].IsAlive)
            {
                // 线程会在下次循环时检查_currentThreadCount并自动退出
            }
        }
    }

    private void QueueProcessingLoop(int threadId)
    {
        var localBatch = new List<(int channel, double voltage)>(1000);
        var assignedChannels = AssignChannelsToThread(threadId);

        while (_processingActive)
        {
            if (threadId >= _currentThreadCount)
            {
                break;
            }

            try
            {
                localBatch.Clear();
                bool hasData = false;

                foreach (int channel in assignedChannels)
                {
                    if (_channelDataQueues.ContainsKey(channel))
                    {
                        var queue = _channelDataQueues[channel];
                        int batchCount = 0;
                        int maxBatchSize = CalculateBatchSize(queue.Count);

                        while (batchCount < maxBatchSize && queue.TryDequeue(out double voltage))
                        {
                            localBatch.Add((channel, voltage));
                            batchCount++;
                            hasData = true;
                        }
                    }
                }

                if (hasData)
                {
                    ProcessBatchToPanel(localBatch, threadId);
                    Interlocked.Add(ref _totalPointsMapped, localBatch.Count);
                }
                else
                {
                    int sleepTime = Math.Max(1, 10 / _currentThreadCount);
                    Thread.Sleep(sleepTime);
                }
            }
            catch (Exception ex)
            {
                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[处理线程-{threadId}错误] {ex.Message}");
                }
                Thread.Sleep(10);
            }
        }

        _processingThreads[threadId] = null;
    }

    private int CalculateBatchSize(int queueSize)
    {
        if (queueSize > 1000) return 500;
        if (queueSize > 100) return 200;
        if (queueSize > 10) return 50;
        return Math.Max(1, queueSize);
    }

    private void ProcessBatchToPanel(List<(int channel, double voltage)> batch, int threadId)
    {
        var channelBatches = new Dictionary<int, List<double>>();

        foreach (var (statisticsChannel, voltage) in batch)
        {
            double mappedVoltage = Math.Round(voltage, 2);

            // 修正通道映射：物理通道 → 面板通道
            int panelChannelIndex;
            if (statisticsChannel == 1) // 物理通道1（干扰通道）
            {
                // 干扰通道不显示在面板上，跳过
                continue;
            }
            else // 物理通道2-8 → 面板通道0-6
            {
                panelChannelIndex = statisticsChannel - 2; // 物理通道2→面板通道0, 物理通道3→面板通道1, etc.
            }

            if (panelChannelIndex >= 0 && panelChannelIndex < 7) // 确保在有效范围内（面板通道0-6）
            {
                if (!channelBatches.ContainsKey(panelChannelIndex))
                {
                    channelBatches[panelChannelIndex] = new List<double>();
                }

                channelBatches[panelChannelIndex].Add(mappedVoltage);
            }
        }

        foreach (var kvp in channelBatches)
        {
            int channelIndex = kvp.Key;
            var voltages = kvp.Value;

            try
            {
                _plotPanel.AddVoltagePointsBatch(channelIndex, voltages);
            }
            catch (Exception ex)
            {
                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[处理线程-{threadId}] 发送数据到面板失败: {ex.Message}");
                }
            }
        }
    }

    private List<int> AssignChannelsToThread(int threadId)
    {
        var channels = new List<int>();
        for (int ch = 1; ch <= 8; ch++)
        {
            if ((ch - 1) % Math.Max(1, _currentThreadCount) == threadId)
            {
                channels.Add(ch);
            }
        }
        return channels;
    }

    private void StopAllProcessingThreads()
    {
        if (_processingThreads != null)
        {
            for (int i = 0; i < _processingThreads.Length; i++)
            {
                var thread = _processingThreads[i];
                if (thread != null && thread.IsAlive)
                {
                    thread.Join(1000);
                }
            }
        }
    }
    #endregion

    #region 数据处理核心循环
    private void DataProcessingLoop()
    {
        var processingBatch = new List<(int channel, double voltage)>(BATCH_SIZE);
        long localProcessedCount = 0;
        int frameProcessCounter = 0;
        var lastReportTime = DateTime.Now;

        if (AppConfig.LogPrint == 1)
        {
            Console.WriteLine("[清理版适配器] 处理线程已启动");
        }

        while (_isRunning)
        {
            try
            {
                int processedInThisCycle = 0;
                var cycleStartTime = DateTime.Now;

                while (processedInThisCycle < BATCH_SIZE && _parser.TryGetResult(out var frameData))
                {
                    frameProcessCounter++;
                    processedInThisCycle += ProcessFrameDataWithAccurateStatistics(frameData, processingBatch, frameProcessCounter);
                }

                if (processingBatch.Count > 0)
                {
                    ProcessVoltageBatch(processingBatch);
                    localProcessedCount += processingBatch.Count;
                    processingBatch.Clear();

                    Interlocked.Add(ref _totalPointsProcessed, localProcessedCount);
                    localProcessedCount = 0;
                }

                // 定期报告处理状态
                var now = DateTime.Now;
                if ((now - lastReportTime).TotalSeconds >= 10 && AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[处理状态] 已处理{frameProcessCounter}帧, 总点数{_totalPointsProcessed}, 队列大小{_totalQueueSize}");
                    lastReportTime = now;
                }

                if (processedInThisCycle == 0)
                {
                    Thread.Sleep(1);
                }
            }
            catch (Exception ex)
            {
                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[清理版适配器错误] {ex.Message}\n{ex.StackTrace}");
                }
                Thread.Sleep(10);
            }
        }

        if (AppConfig.LogPrint == 1)
        {
            Console.WriteLine($"[清理版适配器] 处理线程结束，共处理{frameProcessCounter}帧");
        }
    }

    // 修改 ProcessFrameDataWithAccurateStatistics 方法，添加实时阈值检测：
    private unsafe int ProcessFrameDataWithAccurateStatistics(ParsedFrameData frameData, List<(int, double)> batch, int frameCounter)
    {
        if (frameData?.Channels == null) return 0;

        // 更新适配器统计（用于最终报告和视图映射）- 核心业务逻辑，不受开关控制
        _adapterStatistics.UpdateFrameStatistics(frameData);

        int pointsAdded = 0;
        bool isDetailedLog = _enableDebugOutput && frameCounter <= 3 && AppConfig.LogPrint == 1;

        if (isDetailedLog)
        {
            Console.WriteLine($"[帧处理] 帧{frameCounter}: 通道数={frameData.ChannelCount}");
            foreach (var ch in frameData.Channels)
            {
                Console.WriteLine($"  显示通道{ch.ChannelNumber}: 扣除点={ch.Statistics}, 采样={ch.SampleCount}");
            }
        }

        // 处理采样数据并进行实时阈值检测 - 核心业务逻辑，不受开关控制
        var frameStatistics = new Dictionary<int, (long alphaViolations, long betaViolations, long deductPoints, long sampleCount)>();

        try
        {
            foreach (var channel in frameData.Channels)
            {
                // 确定统计通道号
                int statisticsChannelNumber;
                if (channel.ChannelNumber == 0) // 干扰通道
                {
                    statisticsChannelNumber = 1;
                }
                else // 业务通道1-7 对应 统计通道2-8
                {
                    statisticsChannelNumber = channel.ChannelNumber + 1;
                }

                // 初始化帧统计数据
                long alphaViolations = 0;
                long betaViolations = 0;
                long deductPoints = channel.Statistics;
                long sampleCount = 0;

                if (!channel.IsEmpty && channel.Samples != null && channel.SampleCount > 0)
                {
                    // 获取当前通道的阈值（只对业务通道进行阈值检测）
                    ThresholdData thresholds = new ThresholdData();
                    if (statisticsChannelNumber > 1) // 跳过干扰通道
                    {
                        thresholds = GetChannelThresholdsSafe(statisticsChannelNumber - 1);
                    }

                    // 处理采样数据并进行阈值检测
                    for (int j = 0; j < channel.SampleCount; j++)
                    {
                        var sample = channel.Samples[j];
                        double voltage = sample.Voltage;

                        if (!double.IsNaN(voltage) && !double.IsInfinity(voltage) &&
                            voltage >= -10.0 && voltage <= 10.0)
                        {
                            sampleCount++;

                            // 只对业务通道进行阈值检测
                            if (statisticsChannelNumber > 1)
                            {
                                // 统计属于α范围的点数（当前代码没有这样做）
                                if (voltage >= thresholds.AlphaLow && voltage <= thresholds.AlphaHigh)
                                {
                                    alphaViolations++;  // α有效点数
                                }

                                // 统计属于β范围的点数（当前代码没有这样做）
                                if (voltage >= thresholds.BetaLow && voltage <= thresholds.BetaHigh)
                                {
                                    betaViolations++;   // β有效点数
                                }

                            }

                            batch.Add((statisticsChannelNumber, voltage));
                            pointsAdded++;
                        }
                    }
                }

                // 记录当前帧的统计数据
                frameStatistics[statisticsChannelNumber] = (alphaViolations, betaViolations, deductPoints, sampleCount);
            }

            // 立即更新到ChannelDataManager（实时更新）- 核心业务逻辑，不受开关控制
            foreach (var kvp in frameStatistics)
            {
                int statisticsChannelNumber = kvp.Key;
                var (alphaViolations, betaViolations, deductPoints, sampleCount) = kvp.Value;

                // 修复通道映射：物理通道 → 视图通道
                int viewChannelIndex;
                if (statisticsChannelNumber == 1) // 物理通道1（干扰通道）
                {
                    // 干扰通道不映射到视图，或者映射到特殊位置，这里跳过
                    continue;
                }
                else // 物理通道2-8 → 视图通道1-7
                {
                    viewChannelIndex = statisticsChannelNumber - 2; // 物理通道2→视图通道0, 物理通道3→视图通道1, etc.
                }

                // 确保视图通道索引有效
                if (viewChannelIndex < 0 || viewChannelIndex >= 8)
                {
                    if (AppConfig.LogPrint == 1)
                    {
                        Console.WriteLine($"[通道映射错误] 物理通道{statisticsChannelNumber} → 无效的视图通道{viewChannelIndex}");
                    }
                    continue;
                }

                try
                {
                    bool success = ChannelDataManager.UpdateChannelStatistics(
                        viewChannelIndex,    // 修正：使用视图通道索引 (0-6对应视图通道1-7)
                        alphaViolations,
                        betaViolations,
                        deductPoints,
                        sampleCount);

                    if (AppConfig.LogPrint == 1)
                    {
                        if (!success)
                        {
                            Console.WriteLine($"[实时统计更新失败] 物理通道{statisticsChannelNumber} → 视图通道{viewChannelIndex + 1}");
                        }
                        else
                        {
                            Console.WriteLine($"[通道映射成功] 物理通道{statisticsChannelNumber} → 视图通道{viewChannelIndex + 1} (索引{viewChannelIndex}) 扣除点={deductPoints}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (AppConfig.LogPrint == 1)
                    {
                        Console.WriteLine($"[实时统计更新异常] 物理通道{statisticsChannelNumber} → 视图通道{viewChannelIndex + 1}: {ex.Message}");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"[帧处理错误] 帧{frameCounter}: {ex.Message}");
            }
        }

        if (isDetailedLog)
        {
            Console.WriteLine($"[帧完成] 帧{frameCounter}: 添加点数={pointsAdded}, 统计更新={frameStatistics.Count}个通道");
        }
        return pointsAdded;
    }

    private void ProcessVoltageBatch(List<(int channel, double voltage)> batch)
    {
        foreach (var (channel, voltage) in batch)
        {
            double mappedVoltage = Math.Round(voltage, 2);

            if (_channelDataQueues.ContainsKey(channel))
            {
                _channelDataQueues[channel].Enqueue(mappedVoltage);

                if (_channelDataQueues[channel].Count > 100000)
                {
                    for (int i = 0; i < 10000 && _channelDataQueues[channel].TryDequeue(out _); i++) { }
                }
            }
        }
    }
    #endregion

    #region 视图映射
    // 新增统计数据映射到视图的回调方法：
    private void MapStatisticsToViewCallback(object state)
    {
        if (!_isRunning || _centerView == null || !_statisticsEnabled) return;

        MapCurrentStatisticsToView();
    }

    private void MapCurrentStatisticsToView()
    {
        try
        {
            // 由于已经在ProcessFrameDataWithAccurateStatistics中实时更新ChannelDataManager
            // 这里只需要通知视图刷新显示即可
            try
            {
                // 假设_centerView有通用的刷新方法，如果没有这个方法，可以删除这行
                // _centerView?.RefreshStatisticsDisplay();
                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[统计映射] ChannelDataManager已实时更新，视图应从ChannelDataManager读取最新数据");
                }
            }
            catch (Exception ex)
            {
                if (AppConfig.LogPrint == 1)
                {
                    Console.WriteLine($"[视图刷新失败] {ex.Message}");
                }
            }
        }
        catch (Exception ex)
        {
            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"[统计映射错误] {ex.Message}");
            }
        }
    }
    #endregion

    #region 统计管理
    public void ResetAllStatistics()
    {
        // 重置适配器统计
        _adapterStatistics.StartTime = DateTime.Now;
        _adapterStatistics.TotalFramesProcessed = 0;
        _adapterStatistics.TotalBytesReceived = 0;
        foreach (var stat in _adapterStatistics.ChannelStatistics.Values)
        {
            stat.FrameCount = 0;
            stat.TotalDeductPoints = 0;
            stat.TotalDataPoints = 0;
            stat.TotalDataBytes = 0;
            stat.VoltageSum = 0;
            stat.VoltageCount = 0;
            stat.VoltageMin = double.MaxValue;
            stat.VoltageMax = double.MinValue;
            stat.AdcSum = 0;
            stat.AdcCount = 0;
            stat.AdcMin = int.MaxValue;
            stat.AdcMax = int.MinValue;
        }

        // 重置外部统计系统
        ChannelDataManager.ResetAllChannelStatistics();

        // 立即映射重置后的数据到视图
        if (AppConfig.LogPrint == 1)
        {
            MapCurrentStatisticsToView();
            Console.WriteLine("[清理版适配器] 所有统计数据已重置并映射到视图");
        }
    }
    #endregion

    #region 显示更新和队列清理
    private void UpdateDisplayCallback(object state)
    {
        if (!_isRunning) return;

        try
        {
            int totalPointsUpdated = 0;

            // 修正通道循环：只处理物理通道2-8（跳过干扰通道1）
            for (int statisticsChannel = 2; statisticsChannel <= 8; statisticsChannel++)
            {
                if (!_channelDataQueues.ContainsKey(statisticsChannel)) continue;

                var queue = _channelDataQueues[statisticsChannel];
                int batchCount = 0;
                const int MAX_POINTS_PER_UPDATE = UPDATE_INTERVAL_MS;

                // 计算对应的面板通道索引：物理通道2-8 → 面板通道0-6
                int panelChannelIndex = statisticsChannel - 2;

                while (batchCount < MAX_POINTS_PER_UPDATE && queue.TryDequeue(out double voltage))
                {
                    _plotPanel.AddVoltagePoint(panelChannelIndex, voltage);
                    batchCount++;
                    totalPointsUpdated++;
                }
            }

            if (totalPointsUpdated > 0)
            {
                _plotPanel.UpdateHistogram();
                Interlocked.Add(ref _totalPointsMapped, totalPointsUpdated);
                Interlocked.Increment(ref _totalUpdates);
            }
        }
        catch (Exception ex)
        {
            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"[显示更新错误] {ex.Message}");
            }
        }
    }

    private void DrainAllQueuesParallel()
    {
        var tasks = new List<Task>();

        // 修正通道循环：只处理物理通道2-8（跳过干扰通道1）
        for (int statisticsChannel = 2; statisticsChannel <= 8; statisticsChannel++)
        {
            int ch = statisticsChannel;
            tasks.Add(Task.Run(() => {
                if (_channelDataQueues.ContainsKey(ch))
                {
                    var queue = _channelDataQueues[ch];
                    var batch = new List<double>();
                    int processedCount = 0;

                    // 计算对应的面板通道索引：物理通道2-8 → 面板通道0-6
                    int panelChannelIndex = ch - 2;

                    while (queue.TryDequeue(out double voltage))
                    {
                        batch.Add(voltage);
                        processedCount++;

                        if (batch.Count >= 100)
                        {
                            try
                            {
                                _plotPanel.AddVoltagePointsBatch(panelChannelIndex, batch);
                            }
                            catch (Exception ex)
                            {
                                if (AppConfig.LogPrint == 1)
                                {
                                    Console.WriteLine($"[队列清空] 物理通道{ch}→面板通道{panelChannelIndex}处理失败: {ex.Message}");
                                }
                            }
                            batch.Clear();
                        }
                    }

                    if (batch.Count > 0)
                    {
                        try
                        {
                            _plotPanel.AddVoltagePointsBatch(panelChannelIndex, batch);
                        }
                        catch (Exception ex)
                        {
                            if (AppConfig.LogPrint == 1)
                            {
                                Console.WriteLine($"[队列清空] 物理通道{ch}→面板通道{panelChannelIndex}最后批次处理失败: {ex.Message}");
                            }
                        }
                    }
                }
            }));
        }

        try
        {
            Task.WaitAll(tasks.ToArray(), 5000);
            _plotPanel.UpdateHistogram();
        }
        catch (Exception ex)
        {
            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"[队列清空错误] {ex.Message}");
            }
        }
    }
    #endregion

    #region 资源释放
    public void Dispose()
    {
        Stop();
        _threadAdjustTimer?.Dispose();
        _updateTimer?.Dispose();
        _thresholdRefreshTimer?.Dispose();
        _statisticsUpdateTimer?.Dispose();
        _performanceStopwatch?.Stop();

        foreach (var queue in _channelDataQueues.Values)
        {
            while (queue.TryDequeue(out _)) { }
        }
    }
    #endregion
}

public class ChannelStatistics
{
    public int PhysicalChannelNumber { get; set; }
    public long TotalDeductPoints { get; set; }
    public long TotalDataPoints { get; set; }
    public long AlphaViolations { get; set; }
    public long BetaViolations { get; set; }
    public double AverageVoltage { get; set; }
    public double MinVoltage { get; set; }
    public double MaxVoltage { get; set; }
    public DateTime LastUpdateTime { get; set; }
}

public class AdapterStatistics
{
    public DateTime StartTime { get; set; }
    public long TotalFramesProcessed { get; set; }
    public long TotalBytesReceived { get; set; }
    public readonly Dictionary<int, ChannelStats> ChannelStatistics = new Dictionary<int, ChannelStats>();

    public class ChannelStats
    {
        public int FrameCount { get; set; }
        public long TotalDeductPoints { get; set; }
        public long TotalDataPoints { get; set; }
        public long TotalDataBytes { get; set; }
        public double VoltageSum { get; set; }
        public int VoltageCount { get; set; }
        public double VoltageMin { get; set; } = double.MaxValue;
        public double VoltageMax { get; set; } = double.MinValue;
        public long AdcSum { get; set; }
        public int AdcCount { get; set; }
        public int AdcMin { get; set; } = int.MaxValue;
        public int AdcMax { get; set; } = int.MinValue;
    }

    public AdapterStatistics()
    {
        StartTime = DateTime.Now;
        // 初始化通道1-7的统计
        for (int i = 1; i <= 8; i++)
        {
            ChannelStatistics[i] = new ChannelStats();
        }
    }

    public void UpdateFrameStatistics(ParsedFrameData frameData)
    {
        TotalFramesProcessed++;

        if (frameData?.Channels == null) return;

        foreach (var channel in frameData.Channels)
        {
            // 修正映射逻辑：直接使用物理通道号作为统计通道号
            int physicalChannelNumber;
            int statisticsChannelNumber;

            if (channel.ChannelNumber == 0) // 解析器返回的干扰通道显示为0
            {
                physicalChannelNumber = 1;
                statisticsChannelNumber = 1;
            }
            else // 解析器返回的显示通道1-7对应物理通道2-8
            {
                physicalChannelNumber = channel.ChannelNumber + 1; // 显示通道1-7 → 物理通道2-8
                statisticsChannelNumber = physicalChannelNumber;   // 统计通道与物理通道号一致
            }

            if (AppConfig.LogPrint == 1)
            {
                Console.WriteLine($"[统计映射] 显示通道{channel.ChannelNumber} → 物理通道{physicalChannelNumber} → 统计通道{statisticsChannelNumber}, 扣除点={channel.Statistics}");
            }

            if (ChannelStatistics.ContainsKey(statisticsChannelNumber))
            {
                var stats = ChannelStatistics[statisticsChannelNumber];
                stats.FrameCount++;
                stats.TotalDeductPoints += channel.Statistics;


                if (!channel.IsEmpty && channel.Samples != null)
                {
                    stats.TotalDataPoints += channel.SampleCount;
                    stats.TotalDataBytes += channel.SampleCount * 2;

                    for (int i = 0; i < channel.SampleCount && i < channel.Samples.Length; i++)
                    {
                        var sample = channel.Samples[i];
                        double voltage = sample.Voltage;
                        int adcValue = Math.Abs(sample.RawValue);

                        if (!double.IsNaN(voltage) && !double.IsInfinity(voltage))
                        {
                            stats.VoltageSum += voltage;
                            stats.VoltageCount++;
                            stats.VoltageMin = Math.Min(stats.VoltageMin, voltage);
                            stats.VoltageMax = Math.Max(stats.VoltageMax, voltage);

                            stats.AdcSum += adcValue;
                            stats.AdcCount++;
                            stats.AdcMin = Math.Min(stats.AdcMin, adcValue);
                            stats.AdcMax = Math.Max(stats.AdcMax, adcValue);
                        }
                    }
                }
            }
        }
    }

    public void PrintFinalStatistics()
    {
        var runtime = DateTime.Now - StartTime;

        Console.WriteLine("\n" + new string('=', 110));
        Console.WriteLine("📊 C# 适配器统计总结报告");
        Console.WriteLine(new string('=', 110));

        // 基本统计
        Console.WriteLine($"运行时间: {runtime.TotalSeconds:F1} 秒");
        Console.WriteLine($"处理帧总数: {TotalFramesProcessed}");
        Console.WriteLine($"接收字节总数: {TotalBytesReceived:N0} 字节 ({TotalBytesReceived / 1024.0:F2} KB)");

        if (runtime.TotalSeconds > 0)
        {
            Console.WriteLine($"平均处理速率: {TotalFramesProcessed / runtime.TotalSeconds:F1} 帧/秒, {TotalBytesReceived / runtime.TotalSeconds / 1024:F2} KB/秒");
        }

        Console.WriteLine("\n通道详细统计:");
        Console.WriteLine(new string('-', 110));
        Console.WriteLine($"{"物理通道",-8} {"帧计数",-8} {"扣除点",-10} {"数据点",-10} {"数据字节",-12} {"平均电压",-10} {"电压范围",-20} {"平均ADC",-10}");
        Console.WriteLine(new string('-', 110));

        long totalDeductPoints = 0;
        long totalDataPoints = 0;
        long totalDataBytes = 0;

        // 显示物理通道1-8的统计
        for (int physicalChannel = 1; physicalChannel <= 8; physicalChannel++)
        {
            var stats = ChannelStatistics[physicalChannel];

            if (stats.FrameCount == 0)
            {
                Console.WriteLine($"{physicalChannel,-8} {"0",-8} {"0",-10} {"0",-10} {"0",-12} {"N/A",-10} {"N/A",-20} {"N/A",-10}");
                continue;
            }

            if (physicalChannel == 1) // 干扰通道
            {
                Console.WriteLine($"{physicalChannel,-8} {stats.FrameCount,-8} {stats.TotalDeductPoints,-10} {stats.TotalDataPoints,-10} {stats.TotalDataBytes,-12} {"N/A",-10} {"N/A (干扰通道)",-20} {"N/A",-10}");
            }
            else
            {
                double avgVoltage = stats.VoltageCount > 0 ? stats.VoltageSum / stats.VoltageCount : 0;
                string voltageRange = stats.VoltageCount > 0 ? $"{stats.VoltageMin:F3}V~{stats.VoltageMax:F3}V" : "N/A";
                double avgAdc = stats.AdcCount > 0 ? (double)stats.AdcSum / stats.AdcCount : 0;

                Console.WriteLine($"{physicalChannel,-8} {stats.FrameCount,-8} {stats.TotalDeductPoints,-10} " +
                                $"{stats.TotalDataPoints,-10} {stats.TotalDataBytes,-12} " +
                                $"{avgVoltage,-10:F3} {voltageRange,-20} {avgAdc,-10:F0}");

                totalDeductPoints += stats.TotalDeductPoints;
                totalDataPoints += stats.TotalDataPoints;
                totalDataBytes += stats.TotalDataBytes;
            }
        }

        Console.WriteLine(new string('-', 110));
        Console.WriteLine($"总计 (物理通道2-8): 扣除点={totalDeductPoints}, 数据点={totalDataPoints}, 数据字节={totalDataBytes}");

        // 各通道详细分析
        Console.WriteLine("\n📈 各通道详细分析:");
        Console.WriteLine(new string('-', 110));

        for (int physicalChannel = 1; physicalChannel <= 8; physicalChannel++)
        {
            var stats = ChannelStatistics[physicalChannel];
            if (stats.FrameCount > 0)
            {
                string channelDesc = physicalChannel == 1 ? "(干扰通道)" : $"(业务通道{physicalChannel - 1})";
                Console.WriteLine($"\n物理通道 {physicalChannel} {channelDesc}:");
                Console.WriteLine($"  出现在帧数: {stats.FrameCount} / {TotalFramesProcessed} ({(double)stats.FrameCount / TotalFramesProcessed * 100:F1}%)");
                Console.WriteLine($"  总扣除点数: {stats.TotalDeductPoints}");
                Console.WriteLine($"  总数据点数: {stats.TotalDataPoints}");
                Console.WriteLine($"  总数据字节: {stats.TotalDataBytes} ({stats.TotalDataBytes / 1024.0:F2} KB)");

                if (physicalChannel > 1 && stats.VoltageCount > 0)
                {
                    double avgVoltage = stats.VoltageSum / stats.VoltageCount;
                    double voltageRange = stats.VoltageMax - stats.VoltageMin;
                    double avgAdc = (double)stats.AdcSum / stats.AdcCount;
                    int adcRange = stats.AdcMax - stats.AdcMin;

                    Console.WriteLine($"  电压统计: 平均={avgVoltage:F4}V, 范围={voltageRange:F4}V, 最小={stats.VoltageMin:F4}V, 最大={stats.VoltageMax:F4}V");
                    Console.WriteLine($"  ADC统计:  平均={avgAdc:F0}, 范围={adcRange}, 最小={stats.AdcMin}, 最大={stats.AdcMax}");

                    // 每帧平均数据量
                    double avgDeductPerFrame = (double)stats.TotalDeductPoints / stats.FrameCount;
                    double avgDataPerFrame = (double)stats.TotalDataPoints / stats.FrameCount;
                    double avgBytesPerFrame = (double)stats.TotalDataBytes / stats.FrameCount;

                    Console.WriteLine($"  每帧平均: 扣除点={avgDeductPerFrame:F1}, 数据点={avgDataPerFrame:F1}, 字节数={avgBytesPerFrame:F1}");
                }
            }
        }

        Console.WriteLine(new string('=', 110));
        Console.WriteLine("✅ C# 统计报告完成");
    }
}